package mi.payment.transaction;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.WindowManager;

import mi.payment.constants.Params;
import mi.payment.ui.base.ParentActivity;

/**
 * 继承了此类就可以自动关闭
 */
public class AutoFinishActivity extends ParentActivity {

    private static final int WHAT_FINISH = 0x55;

    private boolean isAutoFinish = true;
    private int mDelayedTime = 60 * 1000;

    public void setAutoFinish(boolean isFinish) {
        isAutoFinish = isFinish;
    }

    public void setDelayed(int delayed) {
        mDelayedTime = delayed;
    }

    @SuppressLint("HandlerLeak")
    private Handler mFinishActivityHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            finish();
        }

    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 如果是外调程序交易不会自动关闭
        if (Params.sL3Params != null) setAutoFinish(false);
    }

    @Override
    protected void onResume() {
        super.onResume();
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (isAutoFinish) {
            mFinishActivityHandler.sendEmptyMessageDelayed(WHAT_FINISH, mDelayedTime);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        mFinishActivityHandler.removeCallbacksAndMessages(null);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                if (isAutoFinish) {
                    mFinishActivityHandler.removeMessages(WHAT_FINISH);
                    mFinishActivityHandler.sendEmptyMessageDelayed(WHAT_FINISH, mDelayedTime);
                }
                break;
        }
        return super.dispatchTouchEvent(ev);
    }


}
